package kr.hkit.androidcomplete03.DomParser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.DomParser.common.DaeguItem;
import kr.hkit.androidcomplete03.DomParser.common.MyAdapterList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class DGDomParse extends Activity {
	final static String TAG = "DEBUG PARSE";
	ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parse);
		list = (ListView) findViewById(R.id.newslistview);
		new ParsingXml().execute("http://www.daegu.go.kr/rss/news.xml");
		Log.d(TAG, "HEY! - onCreate()");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<DaeguItem>> {
		ProgressDialog progressDlg;

		@Override
		protected void onPreExecute() {
			Log.d(TAG, "HEY! - onPreExecute()");
			progressDlg = ProgressDialog.show(DGDomParse.this, "Wait",
					"http://www.daegu.go.kr/rss/news.xml Making ...");
		}

		protected ArrayList<DaeguItem> doInBackground(String... params) {
			Log.d(TAG, "HEY! - doInBackground()");
			StringBuffer sb = new StringBuffer();
			BufferedReader br = null;
			HttpURLConnection con = null;
			String line = null;
			try {
				URL url = new URL(params[0].toString());
				con = (HttpURLConnection) url.openConnection();
				if (con != null) {
					con.setConnectTimeout(10000);
					con.setUseCaches(false);
					if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
						br = new BufferedReader(new InputStreamReader(
								con.getInputStream(), "ks_c_5601-1987"));
					}
				}
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
					con.disconnect();
				} catch (Exception e) {
				}
			}

			return parsingXml(sb.toString());
		}

		@Override
		protected void onPostExecute(ArrayList<DaeguItem> result) {
			Log.d(TAG, "HEY! - onPostExecute()");
			progressDlg.dismiss();

			MyAdapterList adapter = new MyAdapterList(DGDomParse.this, result);
			//MyAdapterList adapter = new MyAdapterList(DGDomParse.this, R.layout.datarow, result);
			
			list.setAdapter(adapter);
		}
	}

	public ArrayList<DaeguItem> parsingXml(String xml) {
		Log.d(TAG, "HEY! - parsingXml()");
		ArrayList<DaeguItem> arList = new ArrayList<DaeguItem>();
		 
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputStream is = new ByteArrayInputStream(xml.getBytes("ks_c_5601-1987"));
            Document doc = builder.parse(is);
 
            Element channel = doc.getDocumentElement();
            NodeList itemTag = channel.getElementsByTagName("item");
 
            //NodeList authorTag = channel.getElementsByTagName("author");
            //NodeList categoryTag = channel.getElementsByTagName("category");
            NodeList titleTag = channel.getElementsByTagName("title");
            NodeList linkTag = channel.getElementsByTagName("link");
            NodeList pubDateTag = channel.getElementsByTagName("pubDate");
            NodeList descriptionTag = channel.getElementsByTagName("description");
 
            for (int i = 0; i < itemTag.getLength(); i++) {
                DaeguItem subItem = new DaeguItem();
                //subItem.setAuthor(authorTag.item(i).getFirstChild().getNodeValue());
                //subItem.setCategory(categoryTag.item(i).getFirstChild()    .getNodeValue());
                subItem.setTitle(titleTag.item(i + 1).getFirstChild().getNodeValue());
                subItem.setLink(linkTag.item(i + 1).getFirstChild().getNodeValue());
                subItem.setPubDate(pubDateTag.item(i).getFirstChild().getNodeValue());
                subItem.setDescription(descriptionTag.item(i + 1).getFirstChild().getNodeValue());
 
                arList.add(subItem);
            }
 
        } catch (Exception e) {
        	
        }
        
        return arList;
	}
}